<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Library of functions and constants for email
 *
 * @package   block_email_list
 * @author    Toni Mas <toni.mas@uib.dot.es>
 * @copyright 2009 by <toni.mas at uib dot es>
 * @license   The source code packaged with this file is Free Software, Copyright (C) 2009 by
 *            <toni.mas at uib dot es>.
 *            It's licensed under the AFFERO GENERAL PUBLIC LICENSE unless stated otherwise.
 *            You can get copies of the licenses here: http://www.affero.org/oagpl.html
 *            AFFERO GENERAL PUBLIC LICENSE is also included in the file called "COPYING".
 */

/**
 * Inbox folder
 */
define('EMAIL_INBOX', 'inbox');

/**
 * Sendbox folder
 */
define('EMAIL_SENDBOX', 'sendbox');

/**
 * Trash folder
 */
define('EMAIL_TRASH', 'trash');

/**
 * Draft folder
 */
define('EMAIL_DRAFT', 'draft');


/// Standard actions

/**
 * View mail
 */
define('EMAIL_VIEWMAIL', 'view');

/**
 * Write mail
 */
define('EMAIL_WRITEMAIL', 'write');

/**
 * Reply mail
 */
define('EMAIL_REPLY', 're');

/**
 * Forward mail
 */
define('EMAIL_FORWARD', 'fw');

/**
 * Reply all mail
 */
define('EMAIL_REPLYALL', 'reall');

/**
 * Edit Draft mail
 */
define('EMAIL_EDITDRAFT', 'edraft');



/**
 * Config PARAMS
 */

/**
 * Enable track mail on user's preference.
 */
define('EMAIL_TRACKBYMAIL', 1);

/**
 * Enable married user folder to this courses on user's preference.
 */
define('EMAIL_MARRIEDFOLDERS2COURSES', 1);

/**
 * Max number of courses who it's unread mails, have display. (on block)
 *
 * Default, no limit
 */
define('EMAIL_MAX_NUMBER_COURSES', 0);


/**
 * Color for answered mails
 *
 */
define('EMAIL_ANSWERED_COLOR', '#83CC83');

/**
 * Odd table fields
 */
define('EMAIL_TABLE_FIELD_COLOR', '#B7B7B7');

/**
 * SBCCMCP-29: Auto refresh rate default secs
 */
define('EMAIL_AUTO_REFRESH_RATE', 600);

 /// DEFAULT CONFIGS

// First, drop old configs .. if exist
if (isset($CFG->email_display_course_principal)) {
    // Default show principal course in blocks who containg list of courses
    unset_config('email_display_course_principal');
}

if (isset($CFG->email_number_courses_display_in_blocks_course)) {
    // Default show all courses
    unset_config('email_number_courses_display_in_blocks_course');
}


/**
 * Function to be run periodically according to the moodle cron
 * This function searches for things that need to be done, such
 * as sending out mail, toggling flags etc ...
 *
 * @return boolean
 **/
function email_cron() {
    return true;
}

/**
 * This function prints to choose mycourses.
 *
 * @param int $courseid Course ID
 * @return boolean Fail or success
 * @uses $USER
 * @todo Finish documenting this function
 */
function email_choose_course($courseid) {
    global $USER;

    // Get my courses
    $mycourses = enrol_get_my_courses();

    $courses = array();
    // Prepare array
    foreach ($mycourses as $mycourse) {
        $courses[$mycourse->id] = $mycourse->fullname;
    }

    // Load participants. This functions avoid selected users from diferents courses. Only select users of one course
    $javascript = '<script type="text/javascript" language="JavaScript">
                <!--
                    function loadParticipants(f) {
                            var www = "participants.php?id="+f.value;
                            window.location.href = www;
                    }
                -->
                </script>';

    // Print javascript
    echo $javascript;

    // Print choose menu of my courses.
    choose_from_menu($courses, 'choose_course', $courseid, 'choose', 'loadParticipants(this);');
}

/**
 * This function get name of file, to the path pass
 *
 * @param string $path File path
 * @return string File name
 * @todo Finish documenting this function
 */
function email_strip_attachment($path) {

    $part = explode('/', $path);

    return $part[count($part)-1];
}

/**
 * This function add copy attachments.
 *
 * @param string $dirsrc           Mail ID source for attached files
 * @param string $mailiddst        Mail ID destiny for attached files
 * @param string $internalmailpath Only use this parametrer in migration of internalmail
 *                                 to email!!! Warning please! PASS ABSOLUTE PATH!!!
 * @param string $attachment       Attachment
 * @return bool True
 * @uses $CFG
 * @uses $OUTPUT
 * @todo Finish documenting this function
 */
function email_copy_attachments($dirsrc, $mailiddst, $internalmailpath=null, $attachment=null) {
    global $CFG, $OUTPUT;

    // Get directory for save this attachments
    $dirsrc = $CFG->dataroot .'/'.$dirsrc;
    $dirdst = email_file_area($mailiddst) .'/'.$attachment;

    if (! $internalmailpath) {
        // Copy this attachments
        if (! copy($dirsrc, $dirdst) ) {
            debugging("src:$dirsrc, dst: $dirdst ");
            print_error('failcopingattachments', 'block_email_list');
        }
    } else {

        if ( file_exists($internalmailpath.'/'.$attachment) ) {
            // Copy attachments but src is internalmail path.
            if (! copy($internalmailpath.'/'.$attachment, $dirdst) ) {
                $OUTPUT->notification('Failed when copying attachmets in migration. src: '
                                     .$internalmailpath.'/'.$attachment.' to dst:'.$dirdst);
            }
        }
    }

    return true;
}

/**
 * This function remove all attachments associated
 * an one mail. First delele records of database, also
 * remove files.
 *
 * @param int $mailid Mail ID
 * @return boolean Success/Fail
 * @uses $OUTPUT
 * @todo Finish documenting this function
 */
function email_delete_attachments($mailid) {
    global $OUTPUT;
    $result = true;

    if ($basedir = email_file_area($mailid)) {

        // Delete all files of mail
        if ($files = get_directory_list($basedir)) {

            foreach ($files as $file) {

                if (! $result = unlink("$basedir/$file")) {
                    echo $OUTPUT->notification("Existing file '$file' has been deleted!");
                }
            }
        }

        // Delete directory as well, if empty
        rmdir("$basedir");
    }

    return $result;
}

/**
 * This functions return string language of root folder (default en)
 *
 * @param string $type Type
 * @return string Name
 * @todo Finish documenting this function
 */
function email_get_root_folder_name($type) {
    $name  = '';
    $types = array(EMAIL_INBOX   => 'inbox',
                   EMAIL_SENDBOX => 'sendbox',
                   EMAIL_TRASH   => 'trash',
                   EMAIL_DRAFT   => 'draft');

    if (array_key_exists($type, $types)) {
        $name = get_string($types[$type], 'block_email_list');
    }

    return $name;
}

/**
 * This function is called recursive for print all subfolders.
 *
 * @param array $subfolders Subfolders to explore.
 * @param int   $userid     User ID
 * @param int   $courseid   Course ID
 * @param bool  $foredit    For edit folders.
 * @param bool  $admin      Admin folders
 * @return string The html representation of the subfolders
 * @uses $CFG
 * @uses $OUTPUT
 * @todo Finish documenting this function
 */
function email_show_subfolders($subfolders, $userid, $courseid, $foredit=false, $admin=false) {
    global $CFG, $OUTPUT;

    $numbermails = 0;
    $unreaded = '';

    // String for alt of img
    $strremove = get_string('removefolder', 'block_email_list');

    $html = array('<ul>');

    $subrow = 0;

    foreach ($subfolders as $subfolder) {
        unset($numbermails);
        unset($unreaded);
        // Get number of unreaded mails
        $numbermails = email_count_unreaded_mails($userid, $courseid, $subfolder->id);

        if ($numbermails > 0) {
            $unreaded = '('.$numbermails.')';
        } else {
            $unreaded = '';
        }

        $html[] = '<li class="r'. $subrow .'">';

        // If edit folder...
        if ($foredit) {

            $html[] = '<a href="'.$CFG->wwwroot.'/blocks/email_list/email/folder.php?course='.$courseid
                .'&amp;id='.$subfolder->id.'&amp;action='.md5('edit').'">'.$subfolder->name.'</a>';
            $html[] = '&#160;&#160;<a href="'.$CFG->wwwroot.'/blocks/email_list/email/folder.php?course='
                .$courseid.'&amp;id='.$subfolder->id.'&amp;action='.md5('edit').'"><img src="'
                .$OUTPUT->pix_url('t/edit') .'" alt="'.$strremove.'" /></a>';
            $html[] = '&#160;&#160;<a href="'.$CFG->wwwroot.'/blocks/email_list/email/folder.php?course='
                .$courseid.'&amp;id='.$subfolder->id.'&amp;action='.md5('remove').'"><img src="'
                .$OUTPUT->pix_url('/t/delete').'" alt="'.$strremove.'" /></a>';

        } else {
            $html[] = '<a href="'.$CFG->wwwroot.'/blocks/email_list/email/index.php?id='.$courseid
                .'&amp;folderid='.$subfolder->id.'">'.$subfolder->name.$unreaded.'</a>';
        }

        // Now, print all subfolders it
        $subfoldersrecursive = email_get_subfolders($subfolder->id, null, $admin);

        // Print recursive all this subfolders
        if ( $subfoldersrecursive ) {
            $html[] = email_show_subfolders($subfoldersrecursive, $userid, $courseid, $foredit, $admin);
        }

        $html[] = '</li>';
        $subrow = $subrow ? 0:1;
    }

    $html[] = '</ul>';
    return implode("\n", $html);
}

/**
 * This function print block for show my folders.
 * Prints all tree
 *
 * @param int $userid   User ID
 * @param int $courseid Course ID
 * @return void
 * @uses $CFG
 * @uses $OUTPUT
 * @todo Finish documenting this function
 */
function email_print_tree_myfolders($userid, $courseid) {
    global $CFG, $OUTPUT;

    $strfolders      = get_string('folders', 'block_email_list');
    $stredit         = get_string('editfolders', 'block_email_list');

    $title   = $strfolders;
    $content = array();
    $footer  = '';

    // Get my folders
    if ($folders = email_get_root_folders($userid)) {

        $numbermails = 0;
        $unreaded = '';
        $row = 0;

        $content[] = '<ul class="c_menu">';

        // Clean trash
        $clean = '';

        // Get courses
        foreach ($folders as $folder) {

            unset($numbermails);
            unset($unreaded);
            // Get number of unreaded mails
            if ($numbermails = email_count_unreaded_mails($userid, $courseid, $folder->id)) {
                $unreaded = ' ('.$numbermails.')';
            } else {
                $unreaded = '';
            }

            if (email_isfolder_type($folder, EMAIL_TRASH)) {
                $clean .= '&#160;&#160;<a href="'.$CFG->wwwroot.'/blocks/email_list/email/folder.php?course='
                        .$courseid.'&amp;folderid='.$folder->id.'&amp;action=cleantrash">'
                        .get_string('cleantrash', 'block_email_list').'</a>';
            }

            // Now, print all subfolders it
            $subfolders = email_get_subfolders($folder->id, $courseid);

            // LI
            $content[] = '<li class="r'. $row .'">';
            $content[] = '<a href="'.$CFG->wwwroot.'/blocks/email_list/email/index.php?id='.$courseid
                       .'&amp;folderid='.$folder->id.'">'.$folder->name.$unreaded.'</a>';

            // If subfolders
            if ( $subfolders ) {
                $content[] = email_show_subfolders($subfolders, $userid, $courseid);
            }
            $content[] = '</li>';
            $row = $row ? 0:1;
        }

        $content[] = '</ul>';

        $footer .= '<div class="footer">'.$clean.'</div>' ."\n";
        // For admin folders
        $footer .= '<div class="footer"><a href="'.$CFG->wwwroot.'/blocks/email_list/email/folder.php?course='
                 . $courseid.'&amp;action='.md5('admin').'"><b>'.$stredit.'</b></a></div>' ."\n";
    }

    $bc = new block_contents();
    $bc->content = implode("\n", $content);
    $bc->footer = $footer;
    $bc->title = $title;
    echo $OUTPUT->block($bc, BLOCK_POS_LEFT);
}

/**
 * This function prints blocks.
 *
 * @param int  $userid           User ID
 * @param int  $courseid         Course ID
 * @param bool $printsearchblock Print search block
 * @return null
 * @uses $CGF
 * @uses $DB
 * @uses $OUTPUT
 * @uses $USER
 * @todo Finish documenting this function
 **/
function email_printblocks($userid, $courseid, $printsearchblock=true) {
    global $CFG, $DB, $OUTPUT, $USER;

    $strcourse  = get_string('course');
    $strcourses = get_string('mailboxs', 'block_email_list');
    $strsearch  = get_string('search');

    $list = array();
    $icons = array();

    if ($printsearchblock) {
        // Print search block
        $form = email_get_search_form($courseid);

        $bc = new block_contents();
        $bc->content = $form;
        $bc->title = $strsearch;
        echo $OUTPUT->block($bc, BLOCK_POS_LEFT);
    }

    // Print my folders
    email_print_tree_myfolders($userid, $courseid);

    // Remove old fields
    unset($list);
    unset($icons);

    // Get my course
    $mycourses = enrol_get_my_courses('id, fullname, visible', null, $CFG->email_max_number_courses);

    $list = array();
    $icons = array();

    $number = 0;

    // Get courses
    foreach ($mycourses as $mycourse) {
        $coursecontext = context_course::instance($mycourse->id);
        $values        = array('blockname' => 'email_list', 'parentcontextid' => $coursecontext->id);
        // Do not display a link to a course unless the course actually has this block installed.
        if (! $DB->record_exists('block_instances', $values)) {
            continue;
        }

        $only_view_current_course_inbox = (0 == $CFG->email_marriedfolders2courses);

        if ($courseid != $mycourse->id && $only_view_current_course_inbox) {
            continue;
        }

        ++$number; // increment for first course

        if ( $number > $CFG->email_max_number_courses && !empty($CFG->email_max_number_courses) ) {
            continue;
        }

        $context = context_course::instance($mycourse->id);


        //Get the number of unread mails
        $numberunreadmails = email_count_unreaded_mails($USER->id, $mycourse->id);
        $unreadmails = '';

        // Only show if has unreaded mails
        if ( $numberunreadmails > 0 ) {
            $unreadmails = '<b>('.$numberunreadmails.')</b>';
            // Define default path of icon for course
            $icon = '<img src="'.$CFG->wwwroot.'/blocks/email_list/email/images/openicon.gif"'
                  .' height="16" width="16" alt="'.$strcourse.'" />';
        } else {
            // Define default path of icon for course
            $icon = '<img src="'.$CFG->wwwroot.'/blocks/email_list/email/icon.gif" height="16"'
                  .' width="16" alt="'.$strcourse.'" />';
        }

        $linkcss = $mycourse->visible ? '' : ' class="dimmed" ';

        // If I'm student
        if ( has_capability('moodle/course:viewhiddencourses', $context) ) {    // Thanks Tim
            // If course visible
            if ( $mycourse->visible ) {
                $list[] = '<a href="'.$CFG->wwwroot.'/blocks/email_list/email/index.php?id='
                        .$mycourse->id.'" '.$linkcss.'>'.$mycourse->fullname .' '. $unreadmails.'</a>';
                $icons[] = $icon;
            }
        } else {
            $list[] = '<a href="'.$CFG->wwwroot.'/blocks/email_list/email/index.php?id='.$mycourse->id
                    .'" '.$linkcss.'>'.$mycourse->fullname .' '. $unreadmails.'</a>';
            $icons[] = $icon;
        }
    }

    if (sizeof($list) > 0) {
        $bc = new block_contents();
        $bc->content = $OUTPUT->list_block_contents($icons, $list);
        $bc->title   = $strcourses;
        // Print block of my courses
        echo $OUTPUT->block($bc, BLOCK_POS_LEFT); // POS LEFT may be wrong, but no way to get a better guess here.
    }
}


/**
 * This fuctions return all subfolders with one folder (one level), if it've
 *
 * @param int  $folderid Folder parent
 * @param int  $courseid Course ID.
 * @param bool $admin    Admin folders
 * @return array Contain all subfolders
 * @uses $DB Gets records
 * @uses $USER
 * @todo Finish documenting this function
 **/
function email_get_subfolders($folderid, $courseid=null, $admin=false) {
    global $DB, $USER;

    // Get childs for this parent
    $childs = $DB->get_records('block_email_list_subfolder', array('folderparentid' => $folderid));

    $subfolders = array();

    // If have childs
    if ($childs) {
        // Save child folder in array
        foreach ($childs as $child) {
            $values = array('id' => $child->folderchildid);

            if (is_null($courseid) or !email_have_asociated_folders($USER->id)) {
                $subfolders[] = $DB->get_record('block_email_list_folder', $values);

            } else {
                $values['course'] = $courseid;

                if ($folder = $DB->get_record('block_email_list_folder', $values)) {
                    $subfolders[] = $folder;
                } else {
                    $values['course'] = 0;

                    if ($folder = $DB->get_record('block_email_list_folder', $values)) {
                        $subfolders[] = $folder; // Add general folder's
                    }
                }
            }
        }
    } else {
        // If no childs, return false
        return false;
    }

    // Return subfolders
    return $subfolders;
}

/**
 * This fuctions return all subfolders with one folder, if it've
 *
 * @param int $folderid Folder parent
 * @return array Contain all subfolders
 * @uses $DB Gets records
 * @todo Finish documenting this function
 **/
function email_get_all_subfolders($folderid) {
    global $DB;

    // Get childs for this parent
    $childs = $DB->get_records('block_email_list_subfolder', array('folderparentid' => $folderid));

    $subfolders = array();

    // If have childs
    if (is_array($childs)) {

        // Save child folder in array
        foreach ($childs as $child) {
            $subfolders[] = $DB->get_record('block_email_list_folder', array('id' => $child->folderchildid));
            $morechilds   = $DB->get_records('block_email_list_subfolder',
                                           array('folderparentid'  =>  $child->folderchildid));

            if (is_array($morechilds)) {
                $childs = array_merge($childs, $morechilds);
            }
        }
    } else {
        // If no childs, return false
        return false;
    }

    // Return subfolders
    return $subfolders;
}

/**
 * This fuctions return the root parent folder, of that folderchild
 *
 * @uses $DB
 * @param int $folderid Folder ID
 * @return Object Contain root parent folder
 * @todo Finish documenting this function
 **/
function email_get_parentfolder($folderid) {
    global $DB;

    // Get parent for this child
    $parent = $DB->get_record('block_email_list_subfolder', array('folderchildid' => $folderid));

    // If has parent
    if ($parent) {

        $folder = email_get_folder($parent->folderparentid);

        // While not find parent root, searching...
        while (is_null($folder->isparenttype)) {
            // Searching ...
            $parent = $DB->get_record('block_email_list_subfolder', array('folderchildid' => $folder->id));
            $folder = email_get_folder($parent->folderparentid);
        }

        return $folder;

    } else {
        // If no parent, return false => FATAL ERROR!
        return false;
    }
}

/**
 * This function return form for searching emails.
 *
 * @param int $courseid Course Id
 * @return string HTML search form
 * @uses $CGF Needs wwwroot
 * @todo Finish documenting this function
 **/
function email_get_search_form($courseid) {
    global $CFG;

    $inputhidden = '<input type="hidden" name="courseid" value="'.$courseid.'" />';

    $form = array('<form method="post" id="searchform" action="'.$CFG->wwwroot
                  .   '/blocks/email_list/email/search.php">',
                  '<table>',
                  '<tr>',
                  '  <td>',
                  '    <input type="text" value="'.get_string('searchtext', 'block_email_list')
                  .    '" name="words" />',
                  '  </td>',
                  '</tr>',
                  '<tr>',
                  '  <td align="center">',
                  '    '. $inputhidden,
                  '    <input type="submit" name="send" value="'.get_string('search').'" />',
                  '  </td>',
                  '</tr>',
                  '<tr valign="top">',
                  '  <td align="center">',
                  '    <a href="'.$CFG->wwwroot.'/blocks/email_list/email/search.php?courseid='
                  .    $courseid.'&amp;action=1">'. get_string('advancedsearch', 'search') .'</a>',
                  '  </td>',
                  '</tr>',
                  '</table>',
                  '</form>');
    return implode($form, "\n");
}

/**
 * This function print formated users to send mail ( This had choosed before )
 *
 * @param array  $users     Users to print.
 * @param bool   $nosenders No users choose (error log)
 * @param object $options   Options for the url
 * @return void
 * @uses $DB
 * @todo Finish documenting this function
 */
function email_print_users_to_send($users, $nosenders=false, $options=null) {
    global $DB;

    $url = '';

    if ($options) {
        $url = email_build_url($options);
    }


    echo '<tr valign="middle">
        <td class="legendmail">
            <b>'.get_string('for', 'block_email_list'). ' :</b>
        </td>
        <td class="inputmail">';

    if (! empty($users)) {

        echo '<div id="to">';

        foreach ($users as $userid) {
            echo '<input type="hidden" value="'.$userid.'" name="to[]" />';
        }

        echo '</div>';

        echo '<textarea id="textareato" class="textareacontacts" name="to" cols="65" rows="3"'
           .' disabled="true" multiple="multiple">';

        foreach ($users as $userid) {
            echo fullname($DB->get_record('user', array('id' => $userid))).', ';
        }

        echo '</textarea>';
    }

    echo '</td><td class="extrabutton">';

    link_to_popup_window('/blocks/email_list/email/participants.php?'.$url, 'participants',
                         get_string('participants', 'block_email_list').' ...', 470, 520,
                         get_string('participants', 'block_email_list'));

    echo '</td></tr>';
    echo "<tr valign=\"middle\">\n  <td class=\"legendmail\">\n  <div id=\"tdcc\"></div>\n  </td>\n"
        ."  <td>\n  <div id=\"fortextareacc\"></div>\n<div id=\"cc\"></div>\n<div id=\"url\">".$urltoaddcc
        .'<span id="urltxt">&#160;|&#160;</span>'.$urltoaddbcc."</div>\n  </td>\n"
        ."  <td>\n  <div id=\"buttoncc\"></div>\n  </td>\n</tr>";
    echo '<tr valign="middle"><td class="legendmail"><div id="tdbcc"></div></td>'
        .'<td><div id="fortextareabcc"></div><div id="bcc"></div></td><td><div id="buttonbcc"></div></td>';


}

/**
 * This function show all participants of one course. Choose user/s to sent mail.
 *
 * @param int $courseid     Course ID
 * @param int $roleid       Role ID
 * @param int $currentgroup Current group
 * @return array Users to sending mail.
 * @uses $CFG
 * @uses $DB
 * @uses $USER
 * @todo Finish documenting this function
 */
function email_choose_users_to_send($courseid, $roleid, $currentgroup) {
    global $CFG, $DB, $USER;

    if (! $course = $DB->get_record('course', array('id' => $courseid))) {
        print_error('invalidcourseid', 'block_email_list');
    }

    // Prepare users to choose us
    if ($courseid) {

        if ($course->id == SITEID) {
            $context = context_system::instance();   // SYSTEM context
        } else {
            $context = context_course::instance($course->id);   // Course context
        }

        // Security issue
        $sitecontext = context_system::instance();
        $frontpagectx = context_course::instance(SITEID);

        if ($context->id != $frontpagectx->id) {
            require_capability('moodle/course:viewparticipants', $context);
        } else {
            require_capability('moodle/site:viewparticipants', $sitecontext);
        }

        $rolenames = array();
        $avoidroles = array();

        if ($roles = get_roles_used_in_context($context, true)) {
            $canviewroles    = get_roles_with_capability('moodle/course:view', CAP_ALLOW, $context);
            $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $sitecontext);

            if (! $CFG->email_add_admins) {
                $adminsroles = get_roles_with_capability('moodle/legacy:admin', CAP_ALLOW, $sitecontext);
            }

            foreach ($roles as $role) {

                if (!isset($canviewroles[$role->id])) {   // Avoid this role (eg course creator)
                    $avoidroles[] = $role->id;
                    unset($roles[$role->id]);
                    continue;
                }

                if (isset($doanythingroles[$role->id])) {   // Avoid this role (ie admin)
                    $avoidroles[] = $role->id;
                    unset($roles[$role->id]);
                    continue;
                }

                if (! $CFG->email_add_admins) {

                    if (isset($adminsroles[$role->id])) {   // Avoid this role (ie admin)
                        $avoidroles[] = $role->id;
                        unset($roles[$role->id]);
                        continue;
                    }
                }

                // Prevent - CONTRIB-609
                if (function_exists('role_get_name')) {
                    $rolenames[$role->id] = strip_tags(role_get_name($role, $context));   // Used in menus etc later on
                } else {
                    $rolenames[$role->id] = strip_tags(format_string($role->name));   // Used in menus etc later on
                }

            }
        }

        // we are looking for all users with this role assigned in this context or higher
        $listofcontexts = array($context->id);

        if ($usercontexts = get_parent_contexts($context)) {
            $listofcontexts = array_merge($usercontexts);
        } else {
            $listofcontexts[] = $sitecontext->id; // must be site
        }

        $values = array();

        $select = 'SELECT u.id, u.username, u.firstname, u.lastname ';

        if ($context->id != $frontpagectx->id) {
            $select = 'SELECT DISTINCT u.id, u.username, u.firstname, u.lastname ';
        }

        $from = ' FROM {user u} '
              . ' LEFT OUTER JOIN {context} ctx'
              .     ' ON (u.id=ctx.instanceid AND ctx.contextlevel = '. CONTEXT_USER .') ';

        if ($context->id != $frontpagectx->id) {
            $from .= ' JOIN {role_assignments} r'
                   .   ' ON u.id=r.userid'
                   . ' LEFT OUTER JOIN {user_lastaccess} ul'
                   .   ' ON (r.userid=ul.userid and ul.courseid = ?) ';
            $values[] = $course->id;
        }

        $hiddensql = has_capability('moodle/role:viewhiddenassigns', $context)? '':' AND r.hidden = 0 ';

        // exclude users with roles we are avoiding
        $adminrolessql = '';
        $adminrolesvalues = array();

        if ($avoidroles) {
            list($adminrolessql, $adminrolesvalues) = $DB->get_in_or_equal($avoidroles);
        }

        $where = ' WHERE u.deleted = 0'
               .   ' AND u.username != ?';
        $values[] = 'guest';

        // join on 2 conditions
        // otherwise we run into the problem of having records in ul table, but not relevant course
        // and user record is not pulled out

        if ($context->id != $frontpagectx->id) {

            if ($roleid) {
                $where .= ' AND r.roleid = ? ';
                $values[] = $roleid;
            }

            list($usql, $params) = $DB->get_in_or_equal($listofcontexts);
            $where .= ' AND '. $usql
                    . ' AND (ul.courseid = ? OR ul.courseid IS null) '
                    . $adminrolessql
                    . $hiddensql;
            $values = array_merge($values, $params, array($course->id), $adminrolesvalues);
        }

        if ($currentgroup && $course->groupmode != 0) {    // Displaying a group by choice
            $from  .= 'LEFT JOIN {groups_members} gm ON u.id = gm.userid ';

            // $currentgroup can be an array of groups id
            if (is_array($currentgroup)) {
                list($usql, $params) = $DB->get_in_or_equal($currentgroup);
                $where .= $usql;
                $values = array_merge($values, $params);
            } else {

                if ($currentgroup == 0) {

                    if (!has_capability('block/email_list:viewallgroups', $context) && $COURSE->groupmode == 1) {
                        $groupids = groups_get_groups_for_user($USER->id, $COURSE->id);
                        list($usql, $params) = $DB->get_in_or_equal($groupids);
                        $where .= $usql;
                        $values = array_merge($values, $params);
                    }
                }
            }

            $where .= 'AND gm.groupid = ?';
            $values[] = $currentgroup;
        }

        $sort = ' ORDER BY u.firstname, u.lastname';

        $userlist = $DB->get_records_sql($select.$from.$where.$sort, $values);


        // $unselectedusers is used in participants.html (included below)
        if ($userlist) {

            foreach ($userlist as $user) {
                $unselectedusers[$user->id] = addslashes(fullname($user,
                        has_capability('moodle/site:viewfullnames', $context)));
            }
        }

        /// If there are multiple Roles in the course, then show a drop down menu for switching
        if (count($rolenames) > 1) {
            echo '<div class="rolesform">';
            echo get_string('currentrole', 'role').': ';
            $rolenames = array(0 => get_string('all')) + $rolenames;
            popup_form("$CFG->wwwroot/blocks/email_list/email/participants.php?id=$courseid"
                      ."&amp;group=$currentgroup&amp;contextid=$context->id&amp;roleid=", $rolenames,
                       'rolesform', $roleid, '');
            echo '</div>';
        }

        // Prints group selector for users with a viewallgroups capability if course groupmode is separate
        echo '<br />';
        groups_print_course_menu($course, $CFG->wwwroot.'/blocks/email_list/email/participants.php?id='.$course->id);
        echo '<br /><br />';
    }

    // Prepare tags for use in participants.html (included below)
    $straddusersto  = get_string('addusersto', 'block_email_list');
    $stradduserscc = get_string('cc', 'block_email_list');
    $straddusersbcc = get_string('bcc', 'block_email_list');
    $stradd = get_string('ok');
    $strto = get_string('to', 'block_email_list');
    $strcc = get_string('cc', 'block_email_list');
    $strbcc = get_string('bcc', 'block_email_list');
    $strselectedusersremove = get_string('selectedusersremove', 'block_email_list');
    $straction = get_string('selectaction', 'block_email_list');
    $strcancel = get_string('cancel');

    // Create an object for define parametrer
    $options = new stdClass();
    $options->id = $courseid;

    // Prepare url for participants.html (included below)
    $toform = email_build_url($options, true);-

    $url = $CFG->wwwroot.'/blocks/email_list/email/sendmail.php';

    if ( $options ) {
        $urlhtml = email_build_url($options);
    }

    include_once('participants.html');
}

/**
 * This function return true or false if barn contains needle.
 *
 * @param string $needle The thing to find
 * @param Array  $barn   Where the thing might be hidden
 * @return bool True or false if barn contains needle
 * @todo Finish documenting this function
 */
function email_contains($needle, $barn) {

    // If not empty ...
    if (! empty ($barn)) {

        // search string
        foreach ($barn as $straw) {

            if ($straw == $needle) {
                return true;
            }
        }
    }

    return false;
}

/**
 * This funcion assign default line on reply or forward mail
 *
 * @param object $user     User
 * @param int    $date     Date on write mail
 * @param bool   $override Whether to override fullname behaviour
 * @return string Default line
 * @todo Finish documenting this function
 */
function email_make_default_line_replyforward($user, $date, $override=false) {

    $line = get_string('on', 'block_email_list').' '. userdate($date). ', '
          .fullname($user, $override).' '. get_string('wrote', 'block_email_list') . ': <br />'."\n";

    return $line;
}


/**
 * This function read folder's to one mail
 *
 * @param object $mailid Mail who has get folder
 * @param int    $userid User ID
 * @return array Folders contains mail
 * @uses $DB Gets records
 * @todo Finish documenting this function
 **/
function email_get_foldermail($mailid, $userid) {
    global $DB;

    // Prepare select
    $sql = 'SELECT f.id, f.name, fm.id as foldermail'
         .' FROM {block_email_list_folder} f'
         .' INNER JOIN {block_email_list_foldermail} fm ON f.id = fm.folderid'
         .' WHERE fm.mailid = ? AND f.userid = ?'
         .' ORDER BY f.timecreated';
    $values = array($mailid, $userid);

    // Return value of select
    return $DB->get_records_sql($sql, $values);
}

/**
 * This function read Id to reference mail and folder
 *
 * @param int $mailid   Mail ID
 * @param int $folderid Folder ID
 * @return object Contain reference
 * @uses $DB Gets a record
 * @todo Finish documenting this function
 **/
function email_get_reference_to_foldermail($mailid, $folderid) {
    global $DB;

    return $DB->get_record('block_email_list_foldermail', array('mailid' => $mailid, 'folderid' => $folderid));
}

/**
 * This function move mail to folder indicated.
 *
 * @param int $mailid       Mail ID
 * @param int $foldermailid Folder Mail ID reference
 * @param int $folderidnew  Folder ID New
 * @return boolean Success/Fail
 * @uses $DB Checks, gets, sets and deletes records
 * @todo Finish documenting this function
 **/
function email_move_to_folder($mailid, $foldermailid, $folderidnew) {
    global $DB;

    if ($DB->record_exists('block_email_list_folder', array('id' => $folderidnew))) {

        // Folder have exist in this new folder?
        if (! $DB->get_record('block_email_list_foldermail',
                              array('mailid' => $mailid, 'folderid' => $folderidnew))) {

            // Change folder reference to mail
            if (! $DB->set_field('block_email_list_foldermail', 'folderid', $folderidnew,
                                 array('id' => $foldermailid, 'mailid' => $mailid))) {
                    return false;
            }

        } else {

            if (! $DB->delete_records('block_email_list_foldermail', array('id' => $foldermailid))) {
                return false;
            }
        }

    } else {
        return false;
    }

    return true;
}

/**
 * This functions print form to create a new folder
 *
 * @return boolean Success/Fail
 * @todo Finish documenting this function
 **/
function email_newfolderform() {

    include_once('folder.php');

    return true;
}

/**
 * This functions created news folders
 *
 * @param object $folder       Folder object
 * @param int    $parentfolder Parent folder
 * @return boolean Success/Fail
 * @uses $DB Inserts records
 * @todo Finish documenting this function
 **/
function email_newfolder($folder, $parentfolder) {
    global $DB;

    // Add actual time
    $folder->timecreated = time();

    // Make sure course field is not null            Thanks Ann.
    if (! isset( $folder->course)) {
        $folder->course = 0;
    }

    // Insert record
    if (! $folder->id = $DB->insert_record('block_email_list_folder', $folder)) {
        return false;
    }

    // Prepare subfolder
    $subfolder = new stdClass();
    $subfolder->folderparentid = $parentfolder;
    $subfolder->folderchildid  = $folder->id;

    // Insert record reference
    if (! $DB->insert_record('block_email_list_subfolder', $subfolder)) {
        return false;
    }

    add_to_log($folder->userid, 'email_list', 'add subfolder', $folder->name);

    return true;
}

/**
 * This function get folders for one user.
 *
 * @param int    $userid User id
 * @param string $sort   Sort order
 * @return object Result set of folders
 * @uses $DB Gets records
 * @todo Finish documenting this function
 **/
function email_get_folders($userid, $sort='id') {
    global $DB;

    return $DB->get_records('block_email_list_folder', array('userid' => $userid), $sort);
}

/**
 * This function get folder.
 *
 * @param int $folderid The folder id
 * @return object Folder object with localized name
 * @uses $DB Get a record
 * @todo Finish documenting this function
 **/
function email_get_folder($folderid) {
    global $DB;

    $folder = new stdClass();

    if ($folder = $DB->get_record('block_email_list_folder', array('id' => $folderid))) {

        if (isset($folder->isparenttype)) {
            // Only change in parent folders
            if (! is_null($folder->isparenttype)) {
                $folders = array(EMAIL_INBOX   => 'inbox',
                                 EMAIL_SENDBOX => 'sendbox',
                                 EMAIL_TRASH   => 'trash',
                                 EMAIL_DRAFT   => 'draft');

                foreach ($folders as $type => $name) {
                    // If is parent ... return language name
                    if (email_isfolder_type($folder, $type)) {
                        $folder->name = get_string($name, 'block_email_list');
                    }
                }
            }
        }
    }

    return $folder;
}

/**
 * This function created, if no exist, the initial folders
 * who are Inbox, Sendbox, Trash and Draft
 *
 * @param int $userid User ID
 * @return boolean Success/Fail If Success return object which id's
 * @uses $DB Counts records and inserts records
 * @todo Finish documenting this function
 **/
function email_create_parents_folders($userid) {
    global $DB;

    /// $folders is an object who contain id's of created folders
    $folders = new stdClass();
    $folder = new stdClass();

    $folder->timecreated = time();
    $folder->userid     = $userid;

    $foldertypes = array(EMAIL_INBOX   => 'inbox',
                         EMAIL_DRAFT   => 'draft',
                         EMAIL_SENDBOX => 'sendbox',
                         EMAIL_TRASH   => 'trash');

    // Insert each mailbox if doesn't exist
    foreach ($foldertypes as $type => $name) {
        $folder->name         = addslashes(get_string($name, 'block_email_list'));
        $folder->isparenttype = $type; // Be careful if you change this field
        $folderid = $name .'id';

        if ($DB->count_records('block_email_list_folder', array('userid' => $userid, 'isparenttype' => $type)) == 0) {

            if (! $folders->$folderid = $DB->insert_record('block_email_list_folder', $folder)) {
                return false;
            }
        }
    }

    return $folders;
}

/**
 * This function remove one folder
 *
 * @param int    $folderid Folder ID
 * @param object $options  Options
 * @return boolean Success/Fail
 * @uses $CFG
 * @uses $DB     Gets records and deletes them
 * @uses $OUTPUT Outputs notifications
 * @todo Finish documenting this function
 **/
function email_removefolder($folderid, $options) {
    global $CFG, $DB, $OUTPUT;

    // Check if this folder have subfolders
    if ($DB->get_record('block_email_list_subfolder', array('folderparentid' => $folderid))) {
        // This folder is parent of other/s folders. Don't remove this
        // Notify
        redirect($CFG->wwwroot.'/blocks/email_list/email/view.php?id='.$options->id.'&amp;action=viewmails',
                '<div class="notifyproblem">'.get_string('havesubfolders', 'block_email_list').'</div>');
    }

    // Get folder
    if ($folders =  $DB->get_records('block_email_list_folder', array('id' => $folderid))) {

        // For all folders . . .
        foreach ($folders as $folder) {

            // Before removing references to foldermail, move this mails to root folder parent.
            if ($foldermails = $DB->get_records('block_email_list_foldermail', array('folderid' => $folder->id))) {

                // Move mails
                foreach ($foldermails as $foldermail) {
                    // Get folder
                    if ($folder = email_get_folder($foldermail->folderid)) {

                        // Get root folder parent
                        if ($parent = email_get_parentfolder($foldermail->folderid)) {

                            // Assign mails it
                            email_move_to_folder($foldermail->mailid, $foldermail->id, $parent->id);
                        } else {
                            print_error('failgetparentfolder', 'block_email_list');
                        }
                    } else {
                        print_error('failreferencemailfolder', 'block_email_list');
                    }
                }

            }

            // Delete all subfolders of this
            // Delete all subfolders of this
            // Delete all filters of this
            // Delete all foldermail references
            $deletes = array('block_email_list_subfolder'  => array('folderparentid' => $folder->id),
                             'block_email_list_subfolder'  => array('folderchildid' => $folder->id),
                             'block_email_list_filter'     => array('folderid' => $folder->id),
                             'block_email_list_foldermail' => array('folderid' => $folder->id));

            foreach ($deletes as $table => $values) {

                if (! $DB->delete_records($table, $values)) {
                    return false;
                }
            }
        }

        // Delete all folders
        if (! $DB->delete_records('block_email_list_folder', array('id' => $folderid))) {
            return false;
        }
    }

    add_to_log($folderid, 'email_list', 'remove subfolder', "$folderid");

    echo $OUTPUT->notification(get_string('removefolderok', 'block_email_list'));

    return true;
}

/**
 * This function admin's folders.
 *
 * @param array $options Options
 * @return void
 * @uses $CFG    Needs wwwroot
 * @uses $DB     Gets records
 * @uses $OUTPUT Formats output
 * @uses $USER   Needs id
 * @todo Finish documenting this function
 **/
function email_print_administration_folders($options) {
    global $CFG, $OUTPUT, $USER;

    $html = array('<form method="post" name="folderform" action="'. $CFG->wwwroot
                 .'/blocks/email_list/email/folder.php?id='. $options->id .'&amp;action=none">',
                  '<table align="center">', '<tr>', '<td>');

    $html[] = $OUTPUT->heading(get_string('editfolder', 'block_email_list'));

    if ($folders = email_get_root_folders($USER->id, false)) {

        $html[] = '<ul>';

        // Has subfolders
        $hassubfolders = false;

        // Get courses
        foreach ($folders as $folder) {
            // Trash folder is not showing
            if (! email_isfolder_type($folder, EMAIL_TRASH) ) {
                $html[] = '<li>'.$folder->name.'</li>';

                // Now, print all subfolders it
                $subfolders = email_get_subfolders($folder->id, null, true);

                // If subfolders
                if ($subfolders) {
                    $html[] = email_show_subfolders($subfolders, $USER->id, $options->course, true, true);
                    $hassubfolders = true;
                }
            }
        }

        $html[] = '</ul>';
    }

    $html[] = '</td></tr></table></form>';

    return array($hassubfolders, implode("\n", $html));
}

/**
 * This function return subfolder if it is.
 *
 * @param int $folderid Folder ID
 * @return object/boolean Return subfolder or false if it isn't subfolder
 * @uses $DB Gets a record
 * @todo Finish documenting this function
 */
function email_is_subfolder($folderid) {
    global $DB;

    return $DB->get_record('block_email_list_subfolder', array('folderchildid' => $folderid));
}

/**
 * This function creates a filter (not yet implemented)
 *
 * @param int $folderid Folder ID
 * @return bool True
 * @uses $OUTPUT
 * @todo Finish writing this function
 */
function email_createfilter($folderid) {
    global $OUTPUT;

    $OUTPUT->notification();

    return true;
}

/**
 * This function modifies a filter (not yet implemented)
 *
 * @param int $filterid Folder ID
 * @return bool True
 * @todo Finish writing this function
 */
function email_modityfilter($filterid) {
    return true;
}

/**
 * This function removes a filter (not yet implemented)
 *
 * @param int $filterid Folder ID
 * @return bool True
 * @todo Finish writing this function
 */
function email_removefilter($filterid) {
    return true;
}

/**
 * This function prints all mails
 *
 * @param int    $userid      User ID
 * @param string $order       Order by ...
 * @param int    $page        The page number
 * @param int    $perpage     The number of rows per page
 * @param object $options     Options for url
 * @param bool   $search      When show mails on search
 * @param array  $mailssearch Mails who has search
 * @return bool Success/Fail
 * @uses $CFG
 * @uses $COURSE
 * @uses $DB
 * @uses $SESSION
 * @todo Finish documenting this function
 **/
function email_showmails($userid, $order = '', $page=0, $perpage=10, $options=null, $search=false, $mailssearch=null) {
    global $CFG, $COURSE, $DB, $SESSION;

    // SSL encription
    if ($CFG->email_enable_ssl) {
        httpsrequired();
    }

    // CONTRIB-690
    if (! empty($_POST['perpage']) and is_numeric($_POST['perpage'])) {
        $SESSION->email_mailsperpage = $_POST['perpage'];

    } else if (!isset($SESSION->email_mailsperpage) or empty($SESSION->email_mailsperpage)) {
        $SESSION->email_mailsperpage = 10; // Default value
    }

	require_once('tablelib.php');
	require_once('email.class.php');

    // Get actual course
    if (! $course = $DB->get_record('course', array('id' => $COURSE->id))) {
        print_error('invalidcourseid', 'block_email_list');
    }

    $contextlevel = CONTEXT_COURSE;

    if ($course->id == SITEID) {
        $contextlevel = CONTEXT_SYSTEM;
        $coursecontext = context_system::instance();
    } else {
        $coursecontext = context_course::instance($course->id);
    }

    $url = '';
    // Build url part options
    if ($options) {
         $url = email_build_url($options);
    }

    /// Print all mails in this HTML file

    // Should use this variable so that we don't break stuff every time a variable is added or changed.
    $baseurl = $CFG->wwwroot.'/blocks/email_list/email/index.php?'.$url. '&amp;page='.$page.'&amp;perpage='.$perpage;

    // Print init form from send data
    $framename = isset($CFG->framename) ? $CFG->framename : '';
    $html = array('<form id="sendmail" action="'. $CFG->wwwroot .'/blocks/email_list/email/index.php?id='
       . $course->id .'&amp;folderid='. $options->folderid .'" method="post" target="'
       . $framename .'" name="sendmail">');

    if ( $course->id == SITEID ) {
        $tablecolumns = array('', 'icon', 'course', 'subject', 'writer', 'timecreated');
    } else {
        $tablecolumns = array('', 'icon', 'subject', 'writer', 'timecreated');
    }

    $folder = null;

    if (isset($options->folderid)) {

        if ($options->folderid != 0) {
            // Get folder
            $folder = email_get_folder($options->folderid);
        } else {
            // solve problem with select an x mails per page for maintein in this folder
            if ( isset($options->folderoldid) && $options->folderoldid != 0 ) {
                $options->folderid = $options->folderoldid;
                $folder = email_get_folder($options->folderid);
            }
        }
    }

    // If actual folder is inbox type, ... change tag showing.
    if (!empty($folder)) {

        if (email_isfolder_type($folder, EMAIL_INBOX)) {
            $strto = get_string('from', 'block_email_list');
        } else {
            $strto = get_string('to', 'block_email_list');
        }
    } else {
        $strto = get_string('from', 'block_email_list');
    }

    $tableheaders = array('', '', get_string('subject', 'block_email_list'), $strto,
                          get_string('date', 'block_email_list'));
    if ( $course->id == SITEID ) {
        $tableheaders = array('', '', get_string('course'), get_string('subject', 'block_email_list'),
                              $strto, get_string('date', 'block_email_list'));
    }

    $table = new email_flexible_table('list-mails-'.$userid);

    $table->define_columns($tablecolumns);
    $table->define_headers($tableheaders);
    $table->define_baseurl($baseurl);

    $table->set_attribute('align', 'center');
    $table->set_attribute('width', '100%');
    $table->set_attribute('class', 'emailtable');

    $table->set_control_variables(array(
        TABLE_VAR_SORT    => 'ssort',
        TABLE_VAR_HIDE    => 'shide',
        TABLE_VAR_SHOW    => 'sshow',
        TABLE_VAR_IFIRST  => 'sifirst',
        TABLE_VAR_ILAST   => 'silast',
        TABLE_VAR_PAGE    => 'spage'
    ));

    $table->sortable(true, 'timecreated', SORT_DESC);

    $table->setup();

    // When no search
    if (! $search) {
        // Count mails
        $result = email_count_mails($userid, $course->id, $table->get_sql_sort(), $options);
        $totalcount = $result->count;
    } else {
        $totalcount = count($mailssearch);
    }

    $table->pagesize($SESSION->email_mailsperpage, $totalcount);

    $table->inputs(true);

    // Now, re-getting emails, apply pagesize (limit)
    if (! $search) {
        // Get mails
        $mails = email_get_mails($userid, $course->id, $table->get_sql_sort(),
                                 $table->get_page_start(), $table->get_page_size(), $options);
    } else {
        $mails = $mailssearch;
    }

    if (empty($mails)) {
        $mails = array();
    }


    $mailsids = email_get_ids($mails);

    // Print all rows
    foreach ($mails as $mail) {

        $attribute = array();
        $email = new eMail();
        $email->set_email($mail);

        $canviewfullnames = has_capability('moodle/site:viewfullnames', $coursecontext);

        if ($folder && email_isfolder_type($folder, EMAIL_SENDBOX)) {
            $struser = $email->get_users_send($canviewfullnames);
        } else {
            $struser = $email->get_fullname_writer($canviewfullnames);
            if (! $email->is_readed($userid, $mail->course)) {
                $attribute = array( 'bgcolor' => $CFG->email_table_field_color);
            }
        }

        if (! isset($options->folderid)) {
            $options->folderid = 0;
        }

        $courseid = $course->id;

        $page   = 'sendmail.php';
        $action = EMAIL_EDITDRAFT;
        $extra  = '';
        if (! email_isfolder_type($folder, EMAIL_DRAFT)) {
            $page   = 'view.php';
            $action = EMAIL_VIEWMAIL;

            if ($course->id == SITEID) {
                $courseid = $mail->course;
            }
            $extra = '&amp;folderid='. $options->folderid .'&amp;mails='. $mailsids;
        }
        $urltosent = '<a href="'.$CFG->httpswwwroot.'/blocks/email_list/email/'. $page .'?id='
                   . $mail->id .'&amp;course='. $courseid .'&amp;action='. $action . $extra .'">'
                   . $mail->subject.'</a>';

        $attachment = '';

        if ($email->has_attachments()) {
            $attachment = '<img src="'. $CFG->httpswwwroot
                        .'/blocks/email_list/email/images/clip.gif" alt="attachment" /> ';
        }

        // Display diferent color if mail is reply or reply all
        $extraimginfo = '';

        if ($email->is_answered($userid, $course->id)) {
            // Color td
            unset($attribute);
            $attribute = array('bgcolor' => $CFG->email_answered_color);

            // Adding info img
            $extraimginfo = '<img src="'.$CFG->wwwroot.'/blocks/email_list/email/images/answered.gif" alt="" /> ';

        }

        if (! $course_mail = $DB->get_record('course', array('id' => $mail->course))) {
            print_error('invalidcourseid', 'block_email_list');
        }

        if ($course->id == SITEID) {
            $table->add_data(array(
                                   '<input id="mail" type="checkbox" name="mailid[]" value="'.$mail->id.'" />',
                                   $course_mail->fullname,
                                   $attachment.$extraimginfo,
                                   $urltosent,
                                   $struser,
                                   userdate($mail->timecreated)),
                              $attribute);
        } else {
            $table->add_data(array(
                                   '<input id="mail" type="checkbox" name="mailid[]" value="'.$mail->id.'" />',
                                   $attachment.$extraimginfo,
                                   $urltosent,
                                   $struser,
                                   userdate($mail->timecreated)),
                              $attribute);
        }
    }

    $html[] = $table->get_html();

    // Print select action, if have mails
    if ($mails) {
        $html[] = email_get_select_options($options, $SESSION->email_mailsperpage);
    }

    // End form
    $html[] = '</form>';

    return implode("\n", $html);
}

/**
 * This functions prints tabs options
 *
 * @param int    $courseid Course Id
 * @param int    $folderid Folder Id
 * @param string $action   Actual action
 * @return boolean Success/Fail
 * @uses $CFG
 * @uses $OUTPUT
 * @todo Finish documenting this function
 */
function email_print_tabs_options($courseid, $folderid, $action=null) {
     global $CFG, $OUTPUT;

     // SSL encription
    if ($CFG->email_enable_ssl) {
        httpsrequired();
        $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
    } else {
        $wwwroot = $CFG->wwwroot;
    }

    $context_type = CONTEXT_COURSE;

    if ($courseid == SITEID) {
        $context_type = CONTEXT_SYSTEM;
        $context = context_system::instance();
    } else {
        $context = context_course::instance($courseid);
    }

    // Declare tab array
    $tabrow = array();

    // Tab for writting new email
    if (has_capability('block/email_list:sendmessage', $context)) {
        $tabrow[] = new tabobject('newmail', $wwwroot.'/blocks/email_list/email/sendmail.php?course='.$courseid.'&amp;folderid='.$folderid,
                  get_string('newmail', 'block_email_list').'&nbsp;<img alt="'.get_string('edit').'" width="15" height="13" src="'.$OUTPUT->pix_url('i/edit').'" />',
                  get_string('newmail', 'block_email_list'));
    }

    if (has_capability('block/email_list:createfolder', $context)) {
        $tabrow[] = new tabobject('newfolderform', $CFG->wwwroot .'/blocks/email_list/email/folder.php?course='.$courseid.'&amp;folderid='.$folderid,
                    get_string('newfolderform', 'block_email_list').'&nbsp;<img alt="'.get_string('edit').'" width="15" height="15" src="'.$CFG->wwwroot.'/blocks/email_list/email/images/folder_add.png" />',
                    get_string('newfolderform', 'block_email_list'));
    }

    // SBCCMCP-36: Tab for lists
    if (has_capability('block/email_list:createlist', $context)) {
        $tabrow[] = new tabobject('editlists', $CFG->wwwroot.'/blocks/email_list/email/list.php?courseid='.$courseid,
                    get_string('editlists', 'block_email_list').'&nbsp;<img alt="'.get_string('editlists', 'block_email_list').'" width="15" height="15" src="'.$OUTPUT->pix_url('i/settings') .'" />',
                    get_string('editlists', 'block_email_list'));
    }

    /// FUTURE: Implement filters
    //$tabrow[] = new tabobject('newfilter', $CFG->wwwroot.'/blocks/email_list/email/view.php?'.$url
    //                         .'&amp;action=\'newfilter\'', get_string('newfilter', 'email') );

    // If empty tabrow, add vspace. Only apply on Site Course.
    if (empty($tabrow)) {
        print($OUTPUT->spacer(array('height' => 50, 'width' => 1)));
    }

    $tabrows = $tabrow;

    // Print tabs, and if it's in case, selected this
    switch($action)    {
        case 'newmail':
        case 'newfolderform':
            $selected = $action;
            break;
        case 'newfilter':
            $selected = 'filter';
            break;
        default:
            $selected = null;
    }

    $output = $OUTPUT->tabtree($tabrows, $selected);
    $output = "\n\n".'<div class="tabtree">'.$output.'</div><div class="clearer"> </div>'."\n\n";
    print($output);

    return true;
}


/**
 * This function get write mails from user
 *
 * @param int    $userid User ID
 * @param string $order  Order by ...
 * @return object Contain all write mails
 * @uses $DB Gets records
 * @todo Finish documenting this function
 **/
function email_get_my_writemails($userid, $order = null) {
    global $DB;

    // Get my write mails
    if ($order) {
        $mails = $DB->get_records('block_email_list_mail', array('userid' => $userid), $order);
    } else {
        $mails = $DB->get_records('block_email_list_mail', array('userid' => $userid));
    }

    return $mails;
}

/**
 * This function makes the query to get or count mails.
 *
 * @param array  $fields    The fields to return from the query
 * @param int    $userid    User ID
 * @param int    $courseid  Course ID
 * @param string $sort      Order by ...
 * @param object $options   Options from get
 * @return array An array with the sql query to fetch the mail and the values for the query
 */
function email_make_query($fields, $userid, $courseid=null, $sort = null, $options = null) {
    $tables = array('{block_email_list_mail} m',
                    'LEFT JOIN {block_email_list_send} s ON m.id = s.mailid',
                    'LEFT JOIN {block_email_list_foldermail} fm ON m.id = fm.mailid');

    // WHERE principal clause for filter userid
    $criteria = array('userid' => 's.userid = :userid', 'folder' => 'fm.folderid = :folder');
    $values   = array('userid' => $userid, 'folder' => 0);

    if ( $courseid != SITEID ) {
        // WHERE principal clause for filter courseid
        $criteria['course'] = 'm.course = :course';
        $values['course']   = $courseid;
    }

    if ($options && isset($options->folderid) && ($options->folderid != 0)) {

        // Get folder
        $folder = email_get_folder($options->folderid);

        $issent  = email_isfolder_type($folder, EMAIL_SENDBOX);
        $isdraft = email_isfolder_type($folder, EMAIL_DRAFT);

        if ($issent || $isdraft) {
            // ALERT!!!! Modify where sql, because now I've show my inbox ==> email_send.userid = myuserid
            $criteria['userid'] = 'm.userid = :userid';

            $criteria['sent'] = 's.sended = :sent';
            $values['sent']   = 1;

            if ($isdraft) {
                $values['sent'] = 0;
                $criteria['sent'] = '(s.sended IS NULL or s.sended = :sent)';
            }
        }

        $values['folder']   = $options->folderid;
    } else {
        /// If no options, I've get inbox, per default get this folder
        // Get folder
        $folder = email_get_root_folder($userid, EMAIL_INBOX);
        $values['folder'] = $folder->id;
    }

    $sortby = array(0 => 'm.timecreated');
    if ($sort) {
        $sortby[0] = $sort;
    }

    $sql = 'SELECT '. implode(',', $fields) . ' FROM '. implode(' ', $tables)
         .' WHERE '. implode(' AND ', $criteria) .' ORDER BY '. implode(', ', $sortby);
    return array($sql, $values);
}

/**
 * This function counts mails.
 *
 * @param int    $userid    User ID
 * @param int    $courseid  Course ID
 * @param string $sort      Order by ...
 * @param string $limitfrom Limit from
 * @param string $limitnum  Limit num
 * @param object $options   Options from get
 * @return object Contain all send mails
 * @uses $DB
 * @todo Finish documenting this function
 */
function email_count_mails($userid, $courseid=null, $sort = null, $options = null) {
    global $DB;

    $fields = array('COUNT(DISTINCT m.id) as count');
    list($sql, $values) = email_make_query($fields, $userid, $courseid, $sort, $options);

    return $DB->get_record_sql($sql, $values);
}

/**
 * This function gets a group of emails.
 *
 * @param int    $userid    User ID
 * @param int    $courseid  Course ID
 * @param string $sort      Order by ...
 * @param string $limitfrom Limit from
 * @param string $limitnum  Limit num
 * @param object $options   Options from get
 * @return object Contain all send mails
 * @uses $DB
 */
function email_get_mails($userid, $courseid=null, $sort = null, $limitfrom = '', $limitnum = '',
                         $options = null) {
    global $DB;

    // For apply order, I've writting an sql clause
    $fields = array('DISTINCT m.id', 'm.userid as writer', 'm.course', 'm.subject', 'm.timecreated',
                    'm.body', 's.toext');

    list($sql, $values) = email_make_query($fields, $userid, $courseid, $sort, $options);

    return $DB->get_records_sql($sql, $values, $limitfrom, $limitnum);
}

/**
 * This function gets all userid unread mails. It don't read trash, draft and send folders.
 * Only used in the cron.
 *
 * @param int $userid User Id.
 * @param int $fromtime The time to start from
 * @return Array All Inbox mails.
 */
function email_get_unread_mails($userid, $fromtime = 0) {
    global $CFG, $DB;

    // Get user courses (don't read hidden courses)
    if ($mycourses = enrol_get_users_courses($userid)) {

        $courses = '';

        foreach ($mycourses as $mycourse) {
            $courses .= (!empty($courses)) ? ','.$mycourse->id : $mycourse->id;
        }

        // Get inbox folder
        if ($folder = email_get_root_folder($userid, EMAIL_INBOX)) {

            $foldersid = $folder->id;

            // Get all subfolders
            if ($subfolders = email_get_all_subfolders($folder->id)) {

                foreach ($subfolders as $subfolder) {
                    $foldersid .= ','.$subfolder->id;
                }
            }

            $sql = 'SELECT s.id, s.userid, s.mailid, s.course
                      FROM {block_email_list_mail} m
                 LEFT JOIN {block_email_list_send} s ON m.id = s.mailid
                 LEFT JOIN {block_email_list_foldermail} fm ON m.id = fm.mailid ';

            // WHERE principal clause for filter by user and course
            $wheresql = ' WHERE s.userid = ? AND s.readed = 0 AND s.sended = 1';
            $values = array($userid);

            if ($fromtime > 0) {
                $wheresql .= " AND m.timecreated > $fromtime";
            }

            if (!empty($courses)) {
                $expanded_courses = explode(',', $courses);
                list($usql, $params) = $DB->get_in_or_equal($expanded_courses);
                $wheresql .= ' AND s.course '.$usql;
                $values = array_merge($values, $params);
            }

            if (!empty($foldersid)) {
                $expanded_folders = explode(',', $foldersid);
                list($usql, $params) = $DB->get_in_or_equal($expanded_folders);
                $wheresql .= ' AND fm.folderid '.$usql;
                $values = array_merge($values, $params);
            }

            return $DB->get_records_sql($sql.$wheresql, $values);
        }
    }

    return array();
}

/**
 * This functions return number of unreaded mails
 *
 * @param int $userid   User ID
 * @param int $courseid Course ID
 * @param int $folderid Folder ID (Optional) When fault this param, return total number of unreaded mails
 * @return int Number of unread mails.
 * @uses $DB Counts records
 * @todo Finish documenting this function
 **/
function email_count_unreaded_mails($userid, $courseid, $folderid=null) {
    global $DB;

    $sql      = 'SELECT count(*) FROM {block_email_list_mail} m ';

    // WHERE principal clause for filter by user and course
    $criteria = array('userid' => 's.userid = ?', 'course' => 's.course = ?');
    $values = array('userid' => $userid, 'course' => $courseid);

    if ((! $folderid) || ($folderid <= 0)) {
        // Get inbox folder
        if ($folder = email_get_root_folder($userid, EMAIL_INBOX)) {
            $foldersids = array($folder->id);

            // Get all subfolders
            if ($subfolders = email_get_all_subfolders($folder->id)) {

                foreach ($subfolders as $subfolder) {
                    $foldersids[] = $subfolder->id;
                }
            }

            $sql .= ' LEFT JOIN {block_email_list_send} s ON m.id = s.mailid'
                  . ' LEFT JOIN {block_email_list_foldermail} fm ON m.id = fm.mailid ';

            // WHERE principal clause for filter by user and course
            $criteria['read'] =  's.readed = ?';
            $values['read'] = 0;
            $criteria['sent'] = 'sended = ?';
            $values['sent'] = 1;

            list($usql, $params) = $DB->get_in_or_equal($foldersids);
            $criteria['folderid'] = 'fm.folderid '. $usql;
            $values = array_merge($values, $params);
            $ok = true;

        } else {
        }
        // return mails unreaded
        // wreturn count_records('email_send', 'userid', $userid, 'course', $courseid, 'readed', 0);
    } else {
        // Get folder
        if (! $folder = email_get_folder($folderid)) {
            return 0;
        }

        $criteria['folderid'] = 'fm.folderid = ?';
        $values[] = $folder->id;

        if (email_isfolder_type($folder, EMAIL_INBOX)) {
            // For apply order, I've writting an sql clause
            $sql .= ' LEFT JOIN {block_email_list_send} s ON m.id = s.mailid'
                  . ' LEFT JOIN {block_email_list_foldermail} fm ON m.id = fm.mailid ';

            $criteria['read'] =  's.readed = ?';
            $values['read'] = 0;
            $criteria['sent'] = 'sended = ?';
            $values['sent'] = 1;
            $ok = true;

        } else if (email_isfolder_type($folder, EMAIL_DRAFT)) {
            // For apply order, I've writting an sql clause
            $sql .= ' LEFT JOIN {block_email_list_foldermail} fm ON m.id = fm.mailid ';
            $criteria['userid'] = 'm.userid = ?';
            $criteria['course'] = 'm.course = ?';
            $ok = true;

        } else {
            return 0;
        }
    }
    if ($ok) {
        $sql .= ' WHERE '. implode(' AND ', $criteria);
        return $DB->count_records_sql($sql, $values);
    }
    return 0;
}

/**
 * This function return success/fail if folder corresponding with this type.
 *
 * @param object $folder Folder Object
 * @param string $type   Type folder
 * @return bool Success/Fail
 * @todo Finish documenting this function
 **/
function email_isfolder_type($folder, $type) {

    if (isset($folder->isparenttype) && $folder->isparenttype) {
        return ($type == $folder->isparenttype);

    } else {

        // Get first parent
        $parentfolder = email_get_parent_folder($folder);

        if (! isset($parentfolder->isparenttype)) {
            return false;
        }

        // Return value
        return ($parentfolder->isparenttype == $type);
    }
}

/**
 * This function return folder parent.
 *
 * @param object $folder Folder
 * @return object Contain parent folder
 * @uses $DB Gets records
 * @todo Finish documenting this function
 **/
function email_get_parent_folder($folder) {
    global $DB;

    if (! $folder) {
        return false;
    }

    $folderid = $folder;

    if (! is_int($folder)) {
        $folder = $folder->id;
    }

    if (! $subfolder = $DB->get_record('block_email_list_subfolder', array('folderchildid' => $folder))) {
        return false;
    }


    return $DB->get_record('block_email_list_folder', array('id' => $subfolder->folderparentid));
}

/**
 * This function return folder parent with it.
 *
 * @param int    $userid User ID
 * @param string $folder Folder
 * @return object Contain parent folder
 * @uses $DB
 * @uses $USER
 * @todo Finish documenting this function
 **/
function email_get_root_folder($userid, $folder) {
    global $DB, $USER;

    if (empty($userid)) {
        $userid = $USER->id;
    }

    email_create_parents_folders($userid);

    $rootfolder = new object();

    if ($userid > 0 and !empty($userid)) {
        $foldernames = array(EMAIL_INBOX   => 'inbox',
                             EMAIL_SENDBOX => 'sendbox',
                             EMAIL_TRASH   => 'trash',
                             EMAIL_DRAFT   => 'draft');

        if (array_key_exists($folder, $foldernames)) {
            $rootfolder = $DB->get_record('block_email_list_folder',
                                          array('userid' => $userid, 'isparenttype' => $folder));
            $rootfolder->name = get_string($foldernames[$folder], 'block_email_list');
            return $rootfolder;
        }
    }

    return $rootfolder;

}

/**
 * This function return my folders. it's recursive function
 *
 * @param int    $folderid  The folder id
 * @param int    $courseid  The course id
 * @param array  $myfolders The folder array
 * @param string $space     The indentation space
 * @return array The list of folders
 */
function email_my_folders($folderid, $courseid, $myfolders, $space) {

    $space .= '&#160;&#160;&#160;';

    $folders = email_get_subfolders($folderid, $courseid);

    if ($folders) {

        foreach ($folders as $folder) {
            $myfolders[$folder->id] = $space.$folder->name;
            $myfolders = email_my_folders($folder->id, $courseid, $myfolders, $space);
        }
    }

    return $myfolders;
}

/**
 * This function return my folders
 *
 * @param int  $userid         User ID
 * @param int  $courseid       Course ID
 * @param bool $excludetrash   Exclude Trash
 * @param bool $excludedraft   Exclude Draft
 * @param bool $excludesendbox Exclude Sendbox
 * @param bool $excludeinbox   Exclude Inbox
 * @return array Contain my folders
 * @todo Finish documenting this function
 */
function email_get_my_folders($userid, $courseid, $excludetrash, $excludedraft,
                              $excludesendbox=false, $excludeinbox=false) {

    // Save my folders in this variable
    $myfolders = array();

    // Get especific root folders
    $folders = email_get_root_folders($userid, !$excludedraft, !$excludetrash,
                                      !$excludesendbox, !$excludeinbox);

    // for every root folder
    foreach ($folders as $folder) {

        $myfolders[$folder->id] = $folder->name;
        $myfolders = email_my_folders($folder->id, $courseid, $myfolders, '&#160;&#160;&#160;');
    }

    return $myfolders;
}

/**
 * This function return root folders parent with it.
 *
 * @param int  $userid  User ID
 * @param bool $draft   Add draft folder
 * @param bool $trash   Add trash folder
 * @param bool $sendbox Add sendbox folder
 * @param bool $inbox   Add inbox folder
 * @return array Contain all parents folders
 * @todo Finish documenting this function
 **/
function email_get_root_folders($userid, $draft=true, $trash=true, $sendbox=true, $inbox=true) {

    email_create_parents_folders($userid);

    $boxes = array(EMAIL_INBOX   => $inbox,
                   EMAIL_DRAFT   => $draft,
                   EMAIL_SENDBOX => $sendbox,
                   EMAIL_TRASH   => $trash);
    $folders = array();

    foreach ($boxes as $box => $check) {

        if ($check) {
            $folders[] = email_get_root_folder($userid, $box);
        }
    }

    return $folders;
}

/**
 * This function gets the users an email was sent to.
 *
 * @param int     $mailid      Mail ID
 * @param bool    $forreplyall Flag indicates if getting user's for reply all. If true return object contain formated names (Optional)
 * @param object  $writer      Contain user who write mail (if not null, exclude this user for returned)
 * @param string  $type        Type of mail for users
 * @return array A list of user objects representing the user the email was sent to
 * @uses $DB
 * @todo Finish documenting this function
 */
function email_get_users_sent($mailid, $forreplyall=false, $writer=null, $type='') {
    global $DB;

    $users = array();

    // Get mails with send to my
    if (! $sends = $DB->get_records('block_email_list_send', array('mailid' => $mailid))) {
        return $users;
    }

    // Get username
    foreach ($sends as $send) {

        // Get user
        if (! $user = $DB->get_record('user', array('id' => $send->userid))) {
            return false;
        }

        // Exclude user
        if ($writer) {

            if ($user->id != $writer->id) {

                if (! $forreplyall ) {
                    $users[] = fullname($user);
                } else {

                    // Separe type, if it's corresponding
                    if (($type == 'to') || ($type == 'cc') || ($type == 'bcc')) {

                        if ($send->type == $type ) {
                            $users[] = $user->id;
                        }

                    } else if ( $type == 'to_ext' ) {

                        if ($send->type == 'to_ext') {
                            $user[] = $send->toext;
                        }

                    } else {
                        $users[] = $user->id;
                    }
                }
            }
        } else {

            if (! $forreplyall ) {

                // Separe type, if it's corresponding
                if (($type == 'to') || ($type == 'cc') || ($type == 'bcc')) {

                    if ($send->type == $type) {
                        $users[] = fullname($user);
                    }

                } else if ( $type == 'to_ext' ) {

                    if ($send->type == 'to_ext') {
                        $user[] = $send->toext;
                    }
                } else {
                    $users[] = fullname($user);
                }
            } else {

                // Separe type, if it's corresponding
                if (($type == 'to') || ($type == 'cc') || ($type == 'bcc')) {

                    if ($send->type == $type) {
                        $users[] = $user->id;
                    }

                } else if ( $type == 'to_ext' ) {

                    if ($send->type == 'to_ext') {
                        $user[] = $send->toext;
                    }
                } else {
                    $users[] = $user->id;
                }
            }
        }
    }

    return $users;
}

/**
 * This function return format fullname users.
 *
 * @param array   $users       Fullname of user's
 * @param boolean $forreplyall If it's true, no return string error (default false)
 * @return string format fullname user's.
 * @todo Finish documenting this function
 */
function email_format_users($users, $forreplyall=false) {

    if ($users) {
        $usersend = '';

        // Index of record
        $i = 0;

        foreach ($users as $user) {

            // If no first record, add semicolon
            if ( $i != 0 ) {
                $usersend .= ', '.$user;
            } else {
                // If first add name only
                $usersend .= $user;
            }

            // Increment index record
            $i++;
        }
    } else {

        if (! $forreplyall) {
            // If no users sent's, inform this act.
            $usersend = get_string('neverusers', 'block_email_list');
        } else {
            $usersend = '';
        }
    }

    // Return string format name's
    return $usersend;
}

/**
 * This functions print select form, who it's options to have mails
 *
 * @param object $options Options for redirect this form
 * @param int    $perpage The number of rows per page
 * @return boolean Success/Fail
 * @uses $CFG
 * @uses $OUTPUT
 * @todo Finish documenting this function
 * */
function email_get_select_options($options, $perpage) {
    global $CFG, $OUTPUT;

    $baseurl = $CFG->wwwroot . '/blocks/email_list/email/index.php?';

    $html = array('<br />','<div class="content emailfloatcontent">');

    if ($options->id != SITEID) {
        $html[] = '<div class="emailfloat emailleft">';

        if (! email_isfolder_type(email_get_folder($options->folderid), EMAIL_SENDBOX)) {
            $html[] = "<select name=\"action\" onchange=\"this.form.submit()\">\n"
                .'  <option value="" selected="selected">' . get_string('markas', 'block_email_list') .":</option>\n"
                .'  <option value="toread">' . get_string('toread', 'block_email_list') . "</option>\n"
                .'  <option value="tounread">' . get_string('tounread', 'block_email_list') . "</option>\n"
                ."</select>\n";

            $html[] = $OUTPUT->spacer(array('height' => 1, 'width' => 20), false);
        }
        $html[] = '</div>';
        $html[] = '<div class="emailleft">';
        $html[] = email_print_movefolder_button($options);

        if (empty($CFG->noemailever) && !empty($CFG->email_enable_external_address)) {
            // SBCCMCP-28: Forwarding to external address configurable
            $html[] = $OUTPUT->spacer(array('height' => 1, 'width' => 5), false);
            $html[] = with_selected_drop_down($options->id);
            $html[] = $OUTPUT->spacer(array('height' => 1, 'width' => 10), false);
        }

        // Idaho State University & MoodleRooms contrib - Thanks!
        $html[] = email_print_preview_button($options->id);
        $html[] = '</div>';
        $html[] = '<div id="move2folder"></div>';
        $html[] = '</div>';

    }

    // ALERT!: Now, I'm printing end start form, for choose number mail per page
    $url = '';
    // Build url part options
    if ($options) {
         $url = email_build_url($options);
    }

    $html[] ='</form>';
    $html[] = '<form id="mailsperpage" name="mailsperpage" action="'. $baseurl . $url.'" method="post">';


    // Choose number mails perpage

    $html[] = '<div id="sizepage" class="emailright">' . get_string('mailsperpage', 'block_email_list') .': ';

    $html[] = '<select name="perpage" onchange="javascript:this.form.submit();">';

    for ($i = 5; $i < 80; $i=$i+5) {

        if ( $perpage == $i ) {
            $html[] = '<option value="'.$i.'" selected="selected">' . $i . '</option>';
        } else {
            $html[] = '<option value="'.$i.'">' . $i . '</option>';
        }
    }

    $html[] = '</select>';
    $html[] = '</div>';

    return implode("\n", $html);
}


/**
 * This function prints select folders combobox, for move any mails
 *
 * @param object $options Options
 * @return void
 * @uses $USER
 */
function email_print_movefolder_button($options) {
    global $USER;

    $courseid = null;

    if ($options->id == SITEID && $options->course != SITEID) {
        $courseid = $options->course;
    } else {
        $courseid = $options->id;
    }

    /// TODO: Changed this function, now cases are had:
    //                        1.- Inbox folder: Only can move to subfolders inbox and trash folder.
    //                        2.- Sendbox and draft folder: Only can move on this subfolders.
    //                        3.- Trash folder: Can move any folder
    if (isset($options->folderid)) {
        // Get folder
        $folderbe = email_get_folder($options->folderid);

    } else if (isset($options->folderoldid)) {
        // Get folder
        $folderbe = email_get_folder($options->folderoldid);

    } else {
        // Inbox folder
        $folderbe = email_get_root_folder($USER->id, EMAIL_INBOX);
    }

    $excludetrash = false;
    $excludedraft = true;
    $excludesend  = true;
    $excludein    = false;

    if (email_isfolder_type($folderbe, EMAIL_SENDBOX)) {
        $excludesend  = false;
        $excludein    = true;

    } else if (email_isfolder_type($folderbe, EMAIL_DRAFT)) {
        $excludein    = true;

    } else if (email_isfolder_type($folderbe, EMAIL_TRASH)) {
        $excludedraft = false;
        $excludesend  = false;
    }

    // Get my folders
    $folders = email_get_my_folders($USER->id, $courseid, $excludetrash, $excludedraft,
                                    $excludesend, $excludein);

    if ($folders) {

        $choose = '';

        // Get my courses
        foreach ($folders as $key => $foldername) {
            $choose .= '<option value="'.$key.'">'. $foldername .'</option>';
        }
    }

    $html = array('<select name="folderid" onchange="addAction(this)">',
                  '  <option value="" selected="selected">'
                . get_string('movetofolder', 'block_email_list')
                . ':</option>'. $choose ."\n</select>");

    // Add 2 space
    $html[] = '&#160;&#160;';

    // Change, now folderoldid is actual folderid
    if (! $options->folderid) {

        if ( $inbox = email_get_root_folder($USER->id, EMAIL_INBOX)) {
            $html[] = '<input type="hidden" name="folderoldid" value="'.$inbox->id.'" />';
        }
    } else {
        $html[] = '<input type="hidden" name="folderoldid" value="'.$options->folderid.'" />';
    }

    // Define action
    //echo '<input type="hidden" name="action" value="move2folder" />';
    // Add javascript for insert person/s who I've send mail

    $javascript = '<script type="text/javascript" language="JavaScript">
                <!--
                        function addAction(form) {

                            var d = document.createElement("div");
                        d.setAttribute("id", "action");
                        var act = document.createElement("input");
                        act.setAttribute("type", "hidden");
                        act.setAttribute("name", "action");
                        act.setAttribute("id", "action");
                        act.setAttribute("value", "move2folder");
                        d.appendChild(act);
                        document.getElementById("move2folder").appendChild(d);

                            document.sendmail.submit();
                        }
                    -->
                 </script>';

    $html[] = $javascript;

    // Print sent button
    //echo '<input type="submit" value="' .get_string('move'). '" onclick="javascript:addAction(this);" />';

    //echo '</div>';
    return implode("\n", $html);
}

/**
 * This funcions build an URL for an options
 *
 * @param object  $options    Options
 * @param boolean $form       If return form
 * @param boolean $arrayinput If name of hidden input is array.
 * @param string  $nameinput  If is arrayinput, pass name of this.
 * @return string URL or Hidden input's
 * @todo Finish documenting this function
 **/
function email_build_url($options, $form=false, $arrayinput=false, $nameinput=null) {
    $url = '';

    // Build url part options
    if ($options) {
         // Index of part url
         $i = 0;

        foreach ($options as $name => $value) {
            // If not first param
            if (! $form ) {

                if ($i != 0) {
                       $url .= '&amp;' .$name .'='. $value;
                } else {
                    // If first param
                    $url .= $name .'='. $value;
                }
                // Increment index
                $i++;
            } else {

                if ( $arrayinput ) {
                    $url .= '<input type="hidden" name="'.$nameinput.'[]" value="'.$value.'" /> ';
                } else {
                    $url .= '<input type="hidden" name="'.$name.'" value="'.$value.'" /> ';
                }
            }
        }
    }

    return $url;
}


/**
 * This functions return id's of object
 *
 * @param object $ids Mail ids
 * @return string String of ids
 * @todo Finish documenting this function
 **/
function email_get_ids($ids) {
    $identities = array();

    if ($ids) {

        foreach ($ids as $id) {
            $identities[] = $id->id;
        }
    }

    // Character alfanumeric, becase optional_param clean anothers tags.
    $strids = implode('a', $identities);

    return $strids;
}

/**
 * This functions return next or previous mail
 *
 * @param int     $mailid         Mail
 * @param string  $mails          Id's of mails
 * @param boolean $nextorprevious True when next, false when previous
 * @return int Next or Previous mail
 * @todo Finish documenting this function
 */
function email_get_nextprevmail($mailid, $mails, $nextorprevious) {

    // To array
    // Character alfanumeric, becase optional_param clean anothers tags.
    $mailsids = explode('a', $mails);

    if ($mailsids) {
        $prev = 0;
        $next = false;

        foreach ($mailsids as $mail) {

            if ( $next ) {
                return $mail; // Return next "record"
            }

            if ( $mail == $mailid ) {

                if ($nextorprevious) {
                    $next = true;
                } else {
                    return $prev; // Return previous "record"
                }
            }
            $prev = $mail;
        }
    }

    return false;
}

/**
 * This function return user who writting an mail
 *
 * @param int $mailid Mail ID
 * @return object User record
 * @uses $DB Gets records
 * @todo Finish documenting this function
 */
function email_get_user($mailid) {
    global $DB;

    // Get mail record
    if (! $mail = $DB->get_record('block_email_list_mail', array('id' => $mailid))) {
        print_error('failgetmail', 'block_email_list');
    }

    // Return user record
    return $DB->get_record('user', array('id' => $mail->userid));
}

/**
 * This function return, if corresponding, preferences button.
 *
 * @param int $courseid Course Id.
 * @return string Preferences button if corresponding.
 * @uses $CFG    Checks email settings
 * @uses $OUTPUT Renders a button
 * @todo Finish documenting this function.
 */
function email_get_preferences_button($courseid) {
    global $CFG, $OUTPUT;

    // Security
    if ( empty($courseid) ) {
        $courseid = SITEID;
    }

    if (empty($CFG->email_trackbymail) and empty($CFG->email_marriedfolders2courses)) {
        return '';
    } else {
        return $OUTPUT->single_button($CFG->wwwroot.'/blocks/email_list/email/preferences.php?id='. $courseid,
                                      get_string('preferences', 'block_email_list'), 'post');
    }
}

/**
 * This function return if userid have aviability or not to associate folder to courses.
 *
 * @param int $userid User Id.
 * @return boolean True or false if have aviability
 * @uses $CFG  Checks if email married folders 2 courses
 * @uses $DB   Gets records
 * @uses $USER Uses $USER->id
 */
function email_have_asociated_folders($userid) {
    global $CFG, $DB, $USER;

    if ( empty($userid) ) {
        $userid = $USER->id;
    }

    if ($CFG->email_marriedfolders2courses) {

        if ( $preferences = $DB->get_record('block_email_list_preference', array('userid' => $userid)) ) {

            if ($preferences->marriedfolders2courses) {
                return true;
            }
        }
    }

    return false;
}

/**
 * This function return special fullname
 * Call general fullname, but it drop all semicolon apears.
 *
 * @param object  $user     The user
 * @param boolean $override Whether to override the default
 * @return string Full name
 */
function email_fullname($user, $override=false) {

    // Drop all semicolon apears. (Js errors when select contacts)
    return str_replace(',', '', fullname($user, $override));
}

/**
 * Displays 'Forward to external address' option when viewing emails.
 * see: SBCCMCP-28; http://tracker.remote-learner.net/browse/SBCCMCP-28
 *
 * @author    Brent Boghosian <brent.boghosian@remote-learner.net>
 * @copyright 2011 Remote Learner - http://www.remote-learner.net/
 * @param int $courseid The course id
 * @return void
 */
function with_selected_drop_down($courseid) {

    $fwdext    = get_string('forwardtoexternal', 'block_email_list');
    $puoptions = 'menubar=0,location=0,scrollbars,resizable,width=600,height=240';
    $alerttext = addslashes(get_string('nochoosemail', 'block_email_list'));

    $onchange = <<< EOT
if (this.value) {
    if (document.sendmail) {
        var ids = get_for_print_multiple_emails(document.sendmail.mail);
    }
    if (ids != '') {
        document.getElementById('withselecteddefault').selected=1;
        return openpopup('/blocks/email_list/email/email2ext.php?courseid={$courseid}&amp;mailids='+ids,
                         'email_forward_ext', '{$puoptions}', 0);
    } else {
        alert('{$alerttext}');
        document.getElementById('withselecteddefault').selected=1;
    }
}
EOT;

    $html = array('<span id="with_selected" class="with_selected">',
                  '<select name="withselected" onchange="'. $onchange. '\">',
                  '<option id="withselecteddefault" value="" selected="selected">'
                  .    get_string('withselected', 'block_email_list')
                  .    '</option>', '<option value="1">'. $fwdext .'</option>', '</select>',
                  '</span>');
    return implode("\n", $html);
}

/**
 * Prints the print emails button
 *
 * Idaho State University & MoodleRooms contrib - Thanks!
 *
 * @param int $courseid Course Id
 * @return void
 */
function email_print_preview_button($courseid) {
    // Action is handled weird, put in a dummy hidden element
    // and then change its name to action when our button has
    // been clicked
    /*echo '<span id="print_preview" class="print_preview">
              <input type="submit" value="'.get_string('printemails', 'block_email_list')
              .'" name="action" onclick="return print_multiple_emails(document.sendmail.mail);" />
              <input type="hidden" value="print" name="disabled" id="printactionid" />
          </span>';
    */
    $html = array('<span id="print_preview" class="print_preview">');
    $html[] = email_print_to_popup_window('button', '/blocks/email_list/email/print.php?courseid='
                     .$courseid .'&amp;mailids=', get_string('printemails', 'block_email_list'),
                                get_string('printemails', 'block_email_list'), true);
    $html[] = '</span>';
    implode("\n", $html);
}

/**
 * Need redefine element_to_popup_window because before get email ids for print. Modify all.
 *
 * @param string  $type     The type of popup to display
 * @param string  $url      The url to display in popup
 * @param string  $linkname The text to display in the link
 * @param string  $title    The popup window title
 * @param boolean $return   Whether to print or return the html
 * @return string Only if $return is true, otherwise null
 * @uses $CFG
 */
function email_print_to_popup_window($type=null, $url=null, $linkname=null, $title=null, $return=false) {
    global $CFG;

    if (is_null($url)) {
        debugging('You must give the url to display in the popup. URL is missing - can\'t create popup window.',
                  DEBUG_DEVELOPER);
    }

    // add some sane default options for popup windows
    $options = 'menubar=0,location=0,scrollbars,resizable,width=500,height=400';

    $name = 'popup';

    // get some default string, using the localized version of legacy defaults
    if (is_null($linkname) || $linkname === '') {
        $linkname = get_string('clickhere');
    }

    if (!$title) {
        $title    = get_string('popupwindowname');
    }

    $fullscreen = 0; // must be passed to openpopup
    $element = '';

    $jscode = ' if (document.sendmail) { var ids = get_for_print_multiple_emails(document.sendmail.mail); }';

    switch ($type) {
        case 'button' :
            $element = '<input type="button" name="'. $name .'" title="'. $title .'" value="'. $linkname .'" '
                      ."onclick=\" $jscode if(ids !='' ) { return openpopup('$url'+ids, '$name',"
                      ." '$options', $fullscreen); } else { alert('"
                      . addslashes(get_string('nochoosemail', 'block_email_list'))."'); } \" />\n";
            break;
        case 'link' :
            // some log url entries contain _SERVER[HTTP_REFERRER] in which case wwwroot is already there.
            if (!(strpos($url, $CFG->wwwroot) === false)) {
                $url = substr($url, strlen($CFG->wwwroot));
            }
            $element = '<a title="'. s(strip_tags($title)) .'" href="'. $CFG->wwwroot . $url .'" '
                     . "onclick=\"this.target='$name'; $jscode if (ids !=''){ return openpopup("
                     . "'$url'+ids, '$name', '$options', $fullscreen); } else { alert('"
                     . addslashes(get_string('nochoosemail', 'block_email_list'))."'); } \">$linkname</a>";
            break;
        default :
            print_error('undefinedelement', 'block_email_list');
            break;
    }

    if ($return) {
        return $element;
    } else {
        echo $element;
    }
}

/**
 * This function sets the number of mails shown per page.
 *
 * @uses $SESSION To set the number of mails shown per page
 * @return void
 */
function email_manage_mailsperpage() {
    global $SESSION;

    $perpage = optional_param('perpage', 0, PARAM_INT);

    if ($perpage > 0) {
        $SESSION->email_mailsperpage = $perpage;
        echo 'Change for: '.$perpage;
    } else {
        $SESSION->email_mailsperpage = 10; // Default value
    }
}


//////////////////////////
//            AJAX        //
//////////////////////////
/**
  * This function returns an object of all users whithin current course who match
  * the search query.
  *  *Modified version of datalib.php's search_user() function
  *
  * @param object  $course          Current Course object
  * @param string  $query           Search query
  * @param boolean $dispadmins      Flag to return course admins or not
  * @param boolean $dispunconfirmed Flag to specify to return unconfirmed users
  * @return object Result set of all matching users
  * @uses $CFG
  * @uses $DB
  * @uses $USER
  * @todo Add option to remove active user from results
 */
function email_search_course_users($course, $query = '', $dispadmins = false, $dispunconfirmed = true) {
    global $CFG, $DB, $USER;

    $firstlike  = $DB->sql_like('u.firstname', '?');
    $lastlike  = $DB->sql_like('u.lastname', '?');
    $order = 'ORDER BY firstname, lastname, id';
    $select = 'u.deleted = 0';
    $values = array();

    if (!$dispunconfirmed) {
        $select .= ' AND u.confirmed = 1';
    }

    if (!$course or $course->id == SITEID) {
        $values = array($query .'%', $query .'%', 'guest');
        $results = $DB->get_records_sql('SELECT u.id, u.firstname, u.lastname, u.email'
              .' FROM {user} u'
              ." WHERE $select"
              .  " AND ($firstlike OR $lastlike)"
              .  ' AND u.username != ?'
              . $order, $values);
    } else {

        $contexttype = CONTEXT_COURSE;

        if ($course->id == SITEID) {
            $contexttype = CONTEXT_SYSTEM;
        }

        $context = context_course::instance($course->id);
        $contextlists = get_related_contexts_string($context);

        // Returns only group(s) members for users without the viewallgroups capability
        $groupmembers = '';
        // Separate groups
        $groupmode = groups_get_course_groupmode($course);
        $groupsql = '';
        $groupvalues = array();

        if ($groupmode == SEPARATEGROUPS && !has_capability('moodle/site:accessallgroups', $context)) {

            // Returns all groups current user is assigned to in course
            if ($groups = groups_get_all_groups($course->id, $USER->id)) {
                $groupmembers = array();

                foreach ($groups as $group) {
                    $groupmembers += groups_get_members($group->id, 'u.id');
                }

                if (!empty($groupmembers)) {
                    list($groupsql, $groupvalues) = $DB->get_in_or_equal(array_keys($groupmembers));
                } else {
                    // Nobody in their groups :(
                    return false;
                }
            } else {
                // They have no group :(
                return false;
            }
        }

        $adminsql = '';
        $adminvalues = array();

        // Hides course admin roles (eg: admin && course creator) if requested (default)
        if (!$dispadmins) {
            $avoidroles = array();

            if ($roles = get_roles_used_in_context($context, true)) {
                $canviewroles    = get_roles_with_capability('moodle/course:view', CAP_ALLOW, $context);
                $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $context);

                if ( ! $CFG->email_add_admins ) {
                    $adminsroles = get_roles_with_capability('moodle/legacy:admin', CAP_ALLOW, $context);
                }

                foreach ($roles as $role) {

                    if (isset($canviewroles[$role->id])) {   // Avoid this role (eg course creator)
                        $avoidroles[] = $role->id;
                        unset($roles[$role->id]);
                        continue;
                    }

                    if (isset($doanythingroles[$role->id])) {   // Avoid this role (ie admin)
                        $avoidroles[] = $role->id;
                        unset($roles[$role->id]);
                        continue;
                    }

                    if ( ! $CFG->email_add_admins ) {

                        if (isset($adminsroles[$role->id])) {   // Avoid this role (ie admin)
                            $avoidroles[] = $role->id;
                            unset($roles[$role->id]);
                            continue;
                        }
                    }
                }
            }

            // exclude users with roles we are avoiding
            if ($avoidroles) {
                list($adminsql, $adminvalues) = $DB->get_in_or_equal($avoidroles, SQL_PARAMS_QM, '', false);
                $adminsql = ' AND ra.roleid '. $adminsql;
            }
        }

        $values = array_merge($values, array($query .'%', $query .'%', 'guest'), $adminvalues, $groupvalues);
        $query = 'SELECT u.id, u.firstname, u.lastname, u.email'
                   .' FROM {user} u, {role_assignments} ra'
                   ." WHERE $select AND ra.contextid $contextlists AND ra.userid = u.id"
                   .  " AND ($firstlike OR $lastlike)"
                   .  ' AND (u.username != ?)'
                   .  " $adminsql $groupsql $order";
         $results = $DB->get_records_sql($query, $values);

    }

    return $results;
}


/**
 * This function show if this block need update.
 *
 * @param int $version eMail List version
 * @return boolean. True if this block must update, or false if block aren't update.
 */
function email_must_update($version) {

    if ( $version < 2009040200 ) {
        return true;
    }
    return false;
}


/**
 * Security function. eMail List has enable for one course?
 *
 * @param int $courseid Course Id.
 * @return boolean True if eMail List block has enabled, else return false.
 * @uses $CFG  Checks my moodle redirect
 * @uses $DB   Gets records from the database
 * @uses $USER Uses user->id
 */
function email_is_enabled_email_list($courseid) {
    global $CFG, $DB, $USER;

    $enabled = false;
    if (empty($courseid)) {
        return $enabled;
    }

    // Get block object
    if ($emaillist = $DB->get_record('block', array('name' => 'email_list'))) {

        if ($courseid != SITEID) {
            $coursecontext = context_course::instance($courseid);
            // Block has enable in this course?
            $valuessql = "SELECT *
                            FROM {block_instances}
                           WHERE blockname = '$emaillist->name'
                             AND parentcontextid = '$coursecontext->id'
                             AND pagetypepattern like '%*'";
            $block = $DB->get_record_sql($valuessql);
        }

        if (empty($block) && $courseid == SITEID) {
            $usercontext = context_user::instance($USER->id);
            // Block has enable on my-moodle
            $values = array('pagetypepattern' => 'my-index',
                            'parentcontextid' => $usercontext->id,
                            'blockname'       => $emaillist->name);
            $block     = $DB->get_record('block_instances', $values);

        }

        if (empty($block)) {
            $sitecontext = context_course::instance(SITEID);
            // Block has enable on site-index
            $values = array('pagetypepattern' => 'site-index',
                            'parentcontextid' => $sitecontext->id,
                            'blockname'       => $emaillist->name);
            $block     = $DB->get_record('block_instances', $values);
        }

        if (! empty($block)) {
            $block_pos = $DB->get_record('block_positions', array('blockinstanceid' => $block->id));

            if (empty($block_pos) || $block_pos->visible) {
                $enabled = has_capability('moodle/block:view', context_block::instance($block->id));
            }
        }
    }
    return $enabled;
}

/**
 * sendmail_external - send mail to external email addresses.
 *
 * @author Brent Boghosian <brent.boghosian@remote-learner.net>
 * @param array  $emailaddrs  Array of email addresses to send to.
 * @param object $user        The mailing USER (from).
 * @param string $subject     The message subject
 * @param string $body        The message text.
 * @param array  $attachments The file attachmemts.
 * @param string &$errorstr   The error string
 * @param int    $wordwrap    The wordwrap setting.
 * @param bool   $ishtml      True if message body is in HTML.
 * @return bool True on success, False on error.
 * @uses $CFG Needs smtphost
 */
function sendmail_external($emailaddrs, $user, $subject, $body, $attachments = null,
                           &$errorstr = null, $wordwrap = 79, $ishtml = true ) {
    global $CFG;

    $mailer = get_mailer();
    $mailer->Sender   = $user->email;
    // ^TBD - see: moodlelib.php::email_to_user() ~ line: 4275
    $mailer->From     = $user->email;
    $mailer->FromName = fullname($user);
    $mailer->AddReplyTo($user->email);
    $mailer->Subject  = substr(stripslashes($subject), 0, 900);

    foreach ($emailaddrs as $addr) {
        $mailer->AddAddress($addr);
    }

    $mailer->WordWrap = $wordwrap;
    $mailer->IsHTML($ishtml);
    $mailer->Body = $body;

    if (! empty($attachments)) {
        //if (debugging()) print_object($attachments);
        $finfo = finfo_open(FILEINFO_MIME_TYPE);

        foreach ($attachments as $attach) {
            $mimetype = finfo_file($finfo, "{$CFG->dataroot}/{$attach->path}/{$attach->contenthash}");
            $mailer->AddAttachment("{$CFG->dataroot}/{$attach->path}/{$attach->contenthash}",
                                   $attach->name, 'base64', $mimetype);
        }
    }

    if (!empty($CFG->smtphosts)) {
        $hostport = explode(':', $CFG->smtphosts);
        $mailer->Host = $hostport[0];
        if (!empty($hostport[1]))
            $mailer->Port = $hostport[1];
    }

    // if (debugging()) print_object($mailer);

    if (! empty($mailer->SMTPDebug)) {
        echo "<pre>\n";
    }

    if (! $mailer->Send()) {

        if ($errorstr != null) {
            $errorstr = $mailer->ErrorInfo;
        }

        // if (debugging()) mtrace('ERROR: '. $mailer->ErrorInfo);
        if (!empty($mailer->SMTPDebug)) {
            echo "</pre>\n";
        }
        return false;
    } else {

        if (!empty($mailer->SMTPDebug)) {
            echo "</pre>\n";
        }
    }
    return true;
}

/**
 * insert_external_list_send  - inserts record for send to external address(es).
 *
 * @author Brent Boghosian <brent.boghosian@remote-learner.net>
 * @param object $email   The email object
 * @param string $toaddrs The list of email addresses (comma , separated)
 * @return bool True on success, false on error
 * @uses $DB
 */
function insert_external_list_send($email, $toaddrs) {
    global $DB;
    // Add "To:" external email addrs in block_email_list_send
    // setting type=> 'to_ext' and new field toext=$toaddrs
    $elso = new stdClass();
    $elso->userid = 0; // $email->userid;
    $elso->course = $email->course;
    $elso->mailid = $email->get_id();
    $elso->type = 'to_ext';
    $elso->readed = 0;
    $elso->sended = 1;
    $elso->answered = 0;
    $elso->toext = $toaddrs;

    return $DB->insert_record('block_email_list_send', $elso);
}

/**
 * maillist_to_users - converts maillists in to, cc, bcc array to userid array;
 * checking to make sure userids remain unique - no duplicates.
 *
 * @author Brent Boghosian <brent.boghosian@remote-learner.net>
 * @param array $ularray Mixed array of userids or comma-separated userids from list.
 * @param array $check2  Optional 2nd array to check for dups.
 * @param array $check3  Optional 3rd array to check for dups.
 * @return array Array of userids
 */
function maillist_to_users( $ularray, $check2=null, $check3=null ) {
    $out = array();

    if (is_array($ularray)) {

        foreach ($ularray as $userids) {

            if (strpos($userids, ',') !== false) { // maillist found
                $innerids = explode(',', $userids);

                foreach ($innerids as $uid) {
                    if ($uid <= 0) {
                        // NOTE: non-AJAX uses negative (-)listid for
                        // unique identifier in browser, must skip over
                        continue;
                    }

                    if ( !in_array($uid, $out) &&
                         ($check2 == null || !in_array($uid, $check2)) &&
                         ($check3 == null || !in_array($uid, $check3)) ) {
                        $out[] = $uid;
                    }
                }

            } else if ( !in_array($userids, $out) &&
                       ($check2 == null || !in_array($userids, $check2)) &&
                       ($check3 == null || !in_array($userids, $check3)) ) {
                $out[] = $userids;
            }
        }
    }
    return $out;
}

/**
 * Get the list of roles that can be emailed
 *
 * Function created as part of code deduplication efforts
 *
 * @author Tyler Bannister <tyler.bannister@remote-learner.net>
 * @param object $context The context to get the roles from
 * @return array Array of roles
 * @uses $CFG
 */
function get_mailable_roles($context) {
    global $CFG;
    $avoidroles = array();
    $sitecontext = context_system::instance();

    if ($roles = get_roles_used_in_context($context, true)) {
        $canviewroles    = get_roles_with_capability('moodle/course:view', CAP_ALLOW, $context);
        $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $sitecontext);

        if (! $CFG->email_add_admins) {
            $adminsroles = get_roles_with_capability('moodle/legacy:admin', CAP_ALLOW, $sitecontext);
        }

        foreach ($roles as $role) {
            $viewable = isset($canviewroles[$role->id]);      // Avoid this role (eg course creator)
            $doall    = isset($doanythingroles[$role->id]);   // Avoid this role (ie admin)
            $admin    = isset($adminsroles[$role->id]);       // Maybe avoid this role (ie admin)

            if ($viewable || $doall || ((! $CFG->email_add_admins ) && $admin)) {
                $avoidroles[] = $role->id;
                unset($roles[$role->id]);
            }
        }
    }
    return array($roles, $avoidroles);
}

/**
 * Output the file
 *
 * @author Tyler Bannister <tyler.bannister@remote-learner.net>
 * @param object $course course settings object
 * @param object $context context object
 * @param string $component the name of the component we are serving files for.
 * @param string $filearea the name of the file area.
 * @param array $args the remaining bits of the file path.
 * @param bool $forcedownload whether the user must be forced to download the file.
 * @return void (no point in returning anything, we have to die per the Moodle design)
 */
function email_list_pluginfile($course, $birecord, $context, $filearea, $args, $forcedownload) {
    $fs = get_file_storage();

    if (!$file = $fs->get_file($context->id, 'block_email_list', $filearea, 0, $filepath, $filename) or $file->is_directory()) {
        send_file_not_found();
    }

    session_get_instance()->write_close(); // unlock session during fileserving
    send_stored_file($file, 0, 0, $forcedownload);
}
